package com.cardmanage.service.impl;


import com.cardmanage.common.RedisConstants;
import com.cardmanage.common.Result;
import com.cardmanage.mapper.LoginMapper;
import com.cardmanage.pojo.NewUser;
import com.cardmanage.pojo.User;
import com.cardmanage.pojo.UserPassword;
import com.cardmanage.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 账号登录验证部分
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final RedisTemplate redisTemplate;
    private final LoginMapper loginMapper;

    /**
     * 登录账号
     * @param user
     * @return
     */
    @Override
    public Result login(User user) {
        int userName = user.getUserName();
        String userPassword = user.getUserPassword();
        Integer userId = loginMapper.login(userName,userPassword);
        if (userId == null){
            return Result.error("账号或密码有误");
        }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String tokenKey = RedisConstants.LOGIN_CODE_KEY + token;
        //存入redis中
        redisTemplate.opsForValue().set(tokenKey,userId);
        redisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        System.out.println(token);
        return Result.success(token);
    }

    /**
     * 账号注册
     * @param newUser
     * @return
     */
    @Override
    public Result createNew(NewUser newUser) {
        Integer userName = newUser.getUserName();
        String userPassword = newUser.getUserPassword();
        String newUserPassword = newUser.getConfirmUserPassword();
        if(!userPassword.equals(newUserPassword)) {
            return Result.error("密码不一致");
        }
        if(!(userName != null && String.valueOf(userName).matches("\\d{8}"))){
            return Result.error("账户名长度必须为8位");
        }
        if(!(userPassword != null && userPassword.length() > 0 && userPassword.length() <= 12)){
            return Result.error("密码长度不在1-12之间");
        }
        try {
            loginMapper.createNew(userName,userPassword);
        } catch (Exception e) {
            System.out.println("该账号已存在");
            return Result.error("该账号已存在");
        }
        Integer userId = loginMapper.login(userName, userPassword);
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String tokenKey = RedisConstants.LOGIN_CODE_KEY + token;
        //存入redis中
        redisTemplate.opsForValue().set(tokenKey,userId);
        redisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.success(token);
    }

    /**
     * 账号退出功能
     * @param request
     * @param response
     * @return
     */
    @Override
    public Result loginOut(HttpServletRequest request, HttpServletResponse response) {
        log.info("执行退出功能");
        String token = request.getHeader("token");
        String tokenKey = RedisConstants.LOGIN_CODE_KEY + token;
        redisTemplate.delete(tokenKey);
//        try {
//            response.sendRedirect(request.getContextPath() + "/user/login?message=退出成功");
//        } catch (IOException e) {
//            System.out.println("退出成功");
//        }
        return Result.success("退出成功");
    }

    /**
     * 修改密码功能
     * @param request
     * @param userPassword
     * @return
     */
    @Override
    public Result Edit(HttpServletRequest request, UserPassword userPassword) {
        String token = request.getHeader("token");
        String tokenKey = RedisConstants.LOGIN_CODE_KEY + token;
        Integer userId = (Integer) redisTemplate.opsForValue().get(tokenKey);
        String userPassword1 = userPassword.getUserPassword();
        String confirmUserPassword = userPassword.getConfirmUserPassword();
        if(!userPassword1.equals(confirmUserPassword)) {
            return Result.error("密码不一致");
        }
        if(!(confirmUserPassword != null && confirmUserPassword.length() > 0 && confirmUserPassword.length() <= 12)){
            return Result.error("新密码长度不在1-12之间");
        }
        try {
            loginMapper.Edit(userId,userPassword1);
        } catch (Exception e) {
            log.info(e.getMessage());
            return Result.error("修改失败");
        }
        return Result.success("修改成功");
    }

}

